import React, { Component } from 'react';
import { connect } from 'dva';

import { Form, Input, Button, notification, Col, Row, InputNumber, Modal, message, Cascader, Icon } from 'antd';
import { UmiComponentProps, FormComponentProps } from '@/common/type';

import { DICT } from '../enum'
import { DropDownSelectObj } from '@/components/DropDownSelect';
import PointSelect from '@/components/PointSelect';

import { DividerItem } from '@/components/DividerItem';
import { MyButton } from '@/styled/form';
import { MyIcon } from '@/components/MyIcon';

import TrimInput, { withTrim } from '@/components/TrimInput'
import styled from 'styled-components'
import { fomatter } from '@/utils/formatter';

const TextArea = withTrim(Input.TextArea);
const MAX = 8;

interface P {
  data?: {
    id?: string;
    valueRuleList: Array<any>;
    pMax?: number; pMin?: number;
    hMax?: number; hMin?: number;
    mapX: string; mapY: string;
    brandId?: string; productId?: string;
    brandName?: string; productName?: string;
    buildId?: string; floorId?: string; areaId?: string;
    buildName?: string; floorName?: string; areaName?: string;
    alias?: any;
  },
  location?: Array<any>;
  brand?: Array<any>;
  dict?: any;
  image?: string;
  lLocation?: boolean;
  lBrand?: boolean;
}
type Props = P & UmiComponentProps & FormComponentProps;

const PIcon = styled(Icon)`
  font-weight: 900;
  font-size: 24px;
  color: #B3B3B3;
  position: absolute;
  top: -3px;
  right: -35px;
  &:hover {
    color: #0880DF;
  }
  transition: color 0.3s ease;
`

@connect(({ device_indoor_hydrant, loading }) => ({
  dict: device_indoor_hydrant.dict || {},
  location: device_indoor_hydrant.location || [],
  brand: device_indoor_hydrant.brand || [],
  image: device_indoor_hydrant.image,
  lLocation: loading.effects['device_indoor_hydrant/queryLocation'],
  lBrand: loading.effects['device_indoor_hydrant/queryBrand']
}))
class FormItem extends Component<Props, any> {
  state = {
    show: false,
    tmpLocation: null
  };

  heightCount = 0;
  pressureCount = 0;

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'device_indoor_hydrant/init', payload: {
        dict: { keyList: DICT },
      }
    })
    if (data) {
      const {
        id,
        mapX, mapY,
        brandId, productId,
        brandName, productName,
        buildId, floorId, areaId,
        buildName, floorName, areaName,
        valueRuleList = [],
        alias = {},
        ...res
      } = data;

      const hnames = [];
      const pnames = [];
      Object.keys(alias).forEach(v => {
        if (v.includes('height')) hnames.push(v)
        if (v.includes('pressure')) pnames.push(v)
      })

      this.heightCount = Math.max(hnames.length - 1, 0);
      this.pressureCount = Math.max(pnames.length - 1, 0);

      const height = valueRuleList.find(v => v.key === 'height') || {};
      const pressure = valueRuleList.find(v => v.key === 'pressure') || {};

      form.setFieldsValue({
        location: mapX && mapY ? `${mapX},${mapY}` : null,
        hMax: height.maxValue,
        hMin: height.minValue,
        pMax: pressure.maxValue,
        pMin: pressure.minValue,
        pressure1: alias.pressure1,
        height1: alias.height1,
        ...res,
        fire: '700190002'
      })
    } else {
      form.setFieldsValue({ type: '43', fire: '700190002' })
    }
  }

  handleMap = () => {
    const { dispatch, form, data } = this.props;
    const { getFieldValue } = form;

    const list = getFieldValue('buildList');
    if ((!Array.isArray(list) || !list[1]) && !data.floorId) {
      message.warn('请选择楼层');
      return;
    }

    dispatch({
      type: 'device_indoor_hydrant/queryFloorImg',
      payload: Array.isArray(list) && list[1] ? list[1].split('%%')[0] : data.floorId
    }).then(() => {
      const { image } = this.props;

      if (!image) {
        message.info('暂无平面图');
        return;
      }

      this.setState({ show: true })
    })
  }

  private getPoi = (arr, key) => {
    return Array.isArray(arr)
      ? arr.findIndex(v => v.key === key)
      : -1;
  }

  handleSubmit = (e) => {
    e.preventDefault();
    const { dispatch, form, data } = this.props;
    form.validateFields((err: undefined | {}, values: any) => {
      if (!err) {
        delete values.height;
        delete values.pressure;

        const res = FOMMATER.map(v => fomatter(
          values[v.list],
          data ? v.names.map(u => data[u]) : null,
          v.len,
          v.names
        ))

        const flag = FOMMATER.every(v => !!v);
        if (
          !flag
        ) {
          notification['error']({
            message: `保存失败`,
            description: '信息录入不规范',
          });
          return;
        }

        const valueRuleList = (data ? data.valueRuleList : []) || [];

        const hInd = this.getPoi(valueRuleList, 'height');
        const pInd = this.getPoi(valueRuleList, 'pressure');

        const hans = {
          key: 'height',
          minValue: values.hMin,
          maxValue: values.hMax,
        };

        const pans = {
          key: 'pressure',
          minValue: values.pMin,
          maxValue: values.pMax,
        };

        hInd === -1 ? valueRuleList.push(hans) : valueRuleList[hInd] = hans;
        pInd === -1 ? valueRuleList.push(pans) : valueRuleList[pInd] = pans;

        let params = {
          valueRuleList,
          mapX: values.location ? values.location.split(',')[0] : data ? data.mapX : null,
          mapY: values.location ? values.location.split(',')[1] : data ? data.mapY : null,
          ...values
        };

        res.forEach(v => {
          params = {
            ...v,
            ...params,
            alias: {}
          }
        })

        delete values.location;
        delete values.buildList;
        delete values.brandList;
        delete params.systemNo;

        Object.entries(params).forEach(v => {
          if (v[0].includes('pressure') || v[0].includes('height')) {
            params.alias[v[0]] = v[1]
            delete params[v[0]]
          }
        })

        data && data.id ? dispatch({
          type: 'device_indoor_hydrant/update',
          payload: {
            id: data.id,
            ...params
          },
        }) : dispatch({
          type: 'device_indoor_hydrant/create',
          payload: params
        })

      } else {
        notification['error']({
          message: `保存失败`,
          description: '信息录入不规范',
        });
      }
    })
  };

  remove = (k, type) => {
    const { form } = this.props;
    const height = form.getFieldValue(type);

    form.setFieldsValue({
      height: height.filter(key => key !== k),
    });
    this[`${type}Count`]--;
  };

  add = (type) => {
    const { form } = this.props;
    const arr = form.getFieldValue(type);
    if (arr.length > MAX - 2) return;
    const nextKeys = arr.concat(this[`${type}Count`]++);
    form.setFieldsValue({
      [type]: nextKeys,
    });
  };

  loadData = (type, selectedOptions) => {

    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `device_indoor_hydrant/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  render() {
    const { form, data, dict = {} } = this.props;
    const { getFieldDecorator, getFieldValue } = form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const subItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 12 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 },
      },
    };

    const noItemLayout = {
      wrapperCol: { span: 14, offset: 6 },
    };

    const Info = DividerItem(data && data.id ? 'form' : 'plus', '室内用水')

    dict['deivce.type'] = {
      '43': '水压检测',
      '67': '液位检测',
    }

    const type = getFieldValue('type');
    getFieldDecorator(`height`, { initialValue: [... new Array(this.heightCount).keys()] });
    getFieldDecorator(`pressure`, { initialValue: [... new Array(this.pressureCount).keys()] });

    if (data && data.id) {
      for (let i = 0; i < this.heightCount; i++) {
        getFieldDecorator(`height${i + 2}`, { initialValue: data.alias[`height${i + 2}`] });
      }
      for (let i = 0; i < this.pressureCount; i++) {
        getFieldDecorator(`pressure${i + 2}`, { initialValue: data.alias[`pressure${i + 2}`] });
      }
    }

    const hformItems = [... new Array(this.heightCount).keys()].map((k, index) => (
      <Form.Item
        {...formItemLayout}
        label={`水位${index + 2}`}
        key={k}
      >
        {getFieldDecorator(`height${k + 2}`, {
          rules: [{ required: type === '67', message: `请输入水位${index + 2}` }],
        })(<TrimInput placeholder={`请输入水位${index + 2}`} />)}
        <PIcon
          type="minus-circle-o"
          onClick={() => this.remove(k, 'height')}
        />
      </Form.Item>
    ));

    const pformItems = [... new Array(this.pressureCount).keys()].map((k, index) => (
      <Form.Item
        {...formItemLayout}
        label={`水压${index + 2}`}
        key={k}
      >
        {getFieldDecorator(`pressure${k + 2}`, {
          rules: [{ required: type === '43', message: `请输入水压${index + 2}` }],
        })(<TrimInput placeholder={`请输入水压${index + 2}`} />)}
        <PIcon
          type="minus-circle-o"
          onClick={() => this.remove(k, 'pressure')}
        />
      </Form.Item>
    ));

    return (
      <Form onSubmit={this.handleSubmit}>
        <Info />
        <Row style={{ minHeight: '75vh' }}>
          <Col span={12}>
            {/* {
              data && data.id && <Form.Item
                {...formItemLayout}
                label="系统编号"
              >
                {getFieldDecorator('systemNo', {
                  rules: [{
                    required: true, message: '请输入系统编号',
                  }],
                })(
                  <TrimInput placeholder='请输入系统编号' disabled />
                )}
              </Form.Item>
            } */}
            <Form.Item
              {...formItemLayout}
              label='设备类型'
            >
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '设备类型' }],
              })(
                (DropDownSelectObj({ dict, type: 'deivce.type', onChange: () => { } }))
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="设备名称"
            >
              {getFieldDecorator('name', {
                rules: [{
                  required: true, message: '请输入设备名称',
                }],
              })(
                <TrimInput placeholder='请输入设备名称' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='安装地址'
              required
            >
              {getFieldDecorator('buildList')(
                <Cascader
                  // disabled={!!(data && data.id)}
                  options={this.props.location}
                  loadData={this.loadData.bind(this, 'queryLocation')}
                  changeOnSelect={this.props.lLocation}
                  placeholder={data ? `${data.buildName || ''}${data.floorName || ''}${data.areaName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            <Form.Item
              {...noItemLayout}
            >
              {getFieldDecorator('installationAddr', {
                rules: [{ required: true, message: '请输入详细地址' }],
              })(
                <TextArea rows={4} style={{ width: '100%', marginTop: '-15px' }} />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='检查类型'
            >
              {getFieldDecorator('fire', {
                rules: [{ required: true, message: '检查类型' }],
              })(
                (DropDownSelectObj({ dict, type: 'device.fire', disabled: true, onChange: () => { } }))
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label="IMEI码"
            >
              {getFieldDecorator('networkAddr', {
                rules: [{
                  required: true, message: '请输入IMEI码',
                }],
              })(
                <TrimInput placeholder='请输入IMEI码' />
              )}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label="S/N码"
            >
              {getFieldDecorator('serialNumber')(
                <TrimInput placeholder='请输入S/N码' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='卡号'
            >
              {getFieldDecorator('cardNo', {
                rules: [{ required: true, message: '请输入卡号', }],
              })(
                <TrimInput placeholder='请输入卡号' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='厂家型号'
              required
            >
              {getFieldDecorator('brandList')(
                <Cascader
                  options={this.props.brand}
                  loadData={this.loadData.bind(this, 'queryBrand')}
                  changeOnSelect={this.props.lBrand}
                  placeholder={data ? `${data.brandName || ''}${data.productName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            <Row style={{ display: type === '43' ? 'block' : 'none' }}>
              <Col span={12}>
                <Form.Item
                  {...subItemLayout}
                  label='水压告警阈值'
                  required
                >
                  {getFieldDecorator('pMin')(
                    <InputNumber placeholder='水压告警阈值' min={0} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
              <Col span={1} style={{ lineHeight: '35px', textAlign: 'center' }}> ~ </Col>
              <Col span={7}>

                <Form.Item>
                  {getFieldDecorator('pMax')(
                    <InputNumber placeholder='水压告警阈值' min={0} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
              <Col span={4}></Col>
            </Row>
            <Row style={{ display: type === '67' ? 'block' : 'none' }}>
              <Col span={12}>
                <Form.Item
                  {...subItemLayout}
                  label='水位告警阈值'
                  required
                >
                  {getFieldDecorator('hMin')(
                    <InputNumber placeholder='水位告警阈值' min={0} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
              <Col span={1} style={{ lineHeight: '35px', textAlign: 'center' }}> ~ </Col>
              <Col span={7}>
                <Form.Item>
                  {getFieldDecorator('hMax')(
                    <InputNumber placeholder='水位告警阈值' min={0} style={{ width: '100%' }} />
                  )}
                </Form.Item>
              </Col>
              <Col span={4}></Col>
            </Row>
{type == 43 &&
            <Form.Item
              {...formItemLayout}
              label='水压1'
            >
              {getFieldDecorator('pressure1', {
                rules: [{ required: type === '43', message: '请输入水压1' }],
              })(
                <TrimInput placeholder='请输入水压1' />
              )}
              <PIcon type="plus-circle" onClick={this.add.bind(this, 'pressure')} />
            </Form.Item>
  }
            {pformItems}
            { type == 67 &&
            <Form.Item
              {...formItemLayout}
              label='水位1'
            >
              {getFieldDecorator('height1', {
                rules: [{ required: type === '67', message: '请输入水位1' }],
              })(
                <TrimInput placeholder='请输入水位1' />
              )}
              <PIcon type="plus-circle" onClick={this.add.bind(this, 'height')} />
            </Form.Item>
  }
            {hformItems}
            <Form.Item
              {...formItemLayout}
              label='平面图坐标'
            >
              {getFieldDecorator('location')(
                <MyButton onClick={this.handleMap}>
                  <MyIcon icon="environment" />选择坐标
                </MyButton>
              )}
              <span>{getFieldValue('location')}</span>
            </Form.Item>
          </Col>
        </Row>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button
          type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
        >保存</Button>
        <Modal
          visible={this.state.show}
          title="平面图坐标"
          width={960}
          okText="保存"
          destroyOnClose={true}
          onCancel={() => this.setState({ show: false, tmpLocation: null })}
          onOk={() => {
            form.setFieldsValue({
              location: this.state.tmpLocation
                ? this.state.tmpLocation.join(',')
                : (data && data.mapX ? `${data.mapX},${data.mapY}` : '')
              })
            this.setState({ show: false, tmpLocation: null })
          }}
        >
          <PointSelect
            image={this.props.image}
            location={getFieldValue('location') ? getFieldValue('location').split(',') : []}
            setPoint={v => this.setState({ tmpLocation: v })}
          />
        </Modal>
      </Form >
    );
  }
}

const FormList = Form.create<Props>({ name: 'dynamic_form_item' })(FormItem);
export default FormList;

const FOMMATER = [{
  names: ['buildId', 'floorId', 'areaId'],
  list: 'buildList',
  len: 2
}, {
  names: ['brandId', 'productId'],
  list: 'brandList',
  len: 2
}]
